<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>

    <script>
        var image = new Image();
        image.setAttribute('crossOrigin', 'anonymous');
        image.src = 'https://yj-community.oss-cn-qingdao.aliyuncs.com/imgs/OOA086Ae9JlAFhEVOq0d5wVo2hhYNQay.jpg';//图片路径
        // image.src = './test.jpg';//图片路径
        // image.src = 'http://p0.meituan.net/wedding/760784a3fdcb09eb2b27a26dccb0aca0345021.jpg%40watermark%3D1%26%26r%3D1%26p%3D9%26x%3D2%26y%3D2%26relative%3D1%26o%3D20';//图片路径
        image.onload = function () {
            var base64 = getBase64Image(image);
            console.log("base64",base64)
        }

        //将图片转成base64 编码
        function getBase64Image(img) {
            var canvas = document.createElement("canvas");
            canvas.width = img.width;
            canvas.height = img.height;
            var ctx = canvas.getContext("2d");
            ctx.drawImage(img, 0, 0, img.width, img.height);
            var ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
            var dataURL = canvas.toDataURL("image/" + ext);
            return dataURL;
        }

    </script>
</body>

</html>